﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.LowLevel
{
    [ModuleDisplay("Add 4")]
    class Add4Module : BaseModule
    {
        private static double[] mDummy;

        private bool hasClearedLast;

        public readonly ModuleInput A;
        public readonly ModuleInput B;
        public readonly ModuleInput C;
        public readonly ModuleInput D;
        public readonly ModuleOutput Out;

        public Add4Module(ModuleManager manager)
            : base(manager)
        {
            // Add input and outputs to module.
            AddInput(A = new ModuleInput("A", IOType.AudioOrWaveform, this));
            AddInput(B = new ModuleInput("B", IOType.AudioOrWaveform, this));
            AddInput(C = new ModuleInput("C", IOType.AudioOrWaveform, this));
            AddInput(D = new ModuleInput("D", IOType.AudioOrWaveform, this));
            AddOutput(Out = new ModuleOutput("Out", IOType.AudioOrWaveform, this));
        }

        public override void ChangeBufferSize(int bufferSize)
        {
            if (mDummy == null || mDummy.Length != bufferSize)
            {
                mDummy = new double[bufferSize];
            }
        }
        
        public override void Process()
        {
            if (A.IsConnected || B.IsConnected || C.IsConnected || D.IsConnected)
            {
                double[] a = A.IsConnected ? A.FromOutput.AudioBuffer.Buffer : mDummy;
                double[] b = B.IsConnected ? B.FromOutput.AudioBuffer.Buffer : mDummy;
                double[] c = C.IsConnected ? C.FromOutput.AudioBuffer.Buffer : mDummy;
                double[] d = D.IsConnected ? D.FromOutput.AudioBuffer.Buffer : mDummy;
                double[] outBuffer = Out.AudioBuffer.Buffer;
                for (int i = 0; i < Out.AudioBuffer.Length; i++)
                {
                    outBuffer[i] = a[i] + b[i] + c[i] + d[i];
                }

                hasClearedLast = false;
            }
            else
            {
                if (!hasClearedLast)
                {
                    hasClearedLast = true;
                    Array.Clear(Out.AudioBuffer.Buffer, 0, Out.AudioBuffer.Length);
                }
            }
        }
    }
}
